package org.lotterm.jconcat;

import java.awt.Image;
import java.awt.Rectangle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class PDFLoader extends Thread {

	private ArrayList<Image> images=new ArrayList<Image>();
	private ArrayList<LoadListener> listeners=new ArrayList<LoadListener>();
	
	private File file;
	
	
	public PDFLoader(File file) {
		this.file=file;
	}
	
	public PDFLoader(File file, LoadListener listener) {
		this.file=file;
		this.listeners.add(listener);
	}
	
	public void addListener(LoadListener listener) {
		this.listeners.add(listener);
	}
	
	public ArrayList<Image> getImages() {
		return this.images;
	}
	
	private void updateStateListeners(float percent) {
		for (LoadListener listener : listeners) {
			listener.updateState(percent);
		}
	}
	
	private void updateErrorListeners(Exception e) {
		for (LoadListener listener : listeners) {
			listener.error(e);
		}
	}
	
	private void updateCompletedListeners() {
		for (LoadListener listener : listeners) {
			listener.completed(this);
		}
	}
	
	@Override
	public void run() {

		System.out.println("One Instance started!");
		try {
			RandomAccessFile raf = new RandomAccessFile(file, "r");

			FileChannel channel = raf.getChannel();
			ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
			PDFFile pdffile = new PDFFile(buf);
	
			for (int i = 1; i <= pdffile.getNumPages(); i++) {
				final PDFPage page = pdffile.getPage(i);
	
				final Rectangle rect = new Rectangle(0, 0, Config.WIDTH, (int) (Config.WIDTH / page
						.getAspectRatio()));
				final Image image = page.getImage((int) rect.getWidth(), (int) rect
						.getHeight(), null, null, true, true);
	
				this.images.add(image);
				
				this.updateStateListeners(((float)i)/((float)pdffile.getNumPages()));
			}
			
			updateCompletedListeners();
			
		} catch (FileNotFoundException e) {
			updateErrorListeners(e);
			e.printStackTrace();
		} catch (IOException e) {
			updateErrorListeners(e);
			e.printStackTrace();
		}
	}
	
}
